// src/pages/FundList/FundList.jsx

import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Spin,
  message,
  Input,
  Modal,
  Form,
  InputNumber,
  Button,
  Tag,
  Tooltip,
  Badge,
} from 'antd';
import { useNavigate } from 'react-router-dom';
import { 
  $fetchFundList,
  $buyFund,
  $sellFund,
} from '../../api/fundApi';
import dayjs from 'dayjs';
import {
  ShoppingCartOutlined,
  DollarOutlined,
  SearchOutlined,
  ArrowUpOutlined,
  RiseOutlined,
  FallOutlined,
  FundOutlined,
} from '@ant-design/icons';
import './FundList.scss';

const { Search } = Input;

/**
 * 从 localStorage 获取已登录的用户 ID
 */
const getUserId = () => {
  const userInfo = localStorage.getItem('user_info');
  if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };
  try {
    return JSON.parse(userInfo).id;
  } catch {
    throw { msg: '用户信息解析失败' };
  }
};

const FundList = () => {
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [loading, setLoading] = useState(false);

  const [isBuyModalVisible, setIsBuyModalVisible] = useState(false);
  const [isSellModalVisible, setIsSellModalVisible] = useState(false);
  const [selectedFund, setSelectedFund] = useState(null);

  const navigate = useNavigate();

  // 1. 页面挂载时拉取基金列表
  useEffect(() => {
    setLoading(true);
    $fetchFundList()
      .then((list) => {
        const formatted = list.map((item) => ({
          code: item.code,
          name: item.name,
          unitNetValue: item.unit_net_value,
          cumulativeNetValue: item.cumulative_net_value,
          dailyGrowthRate: item.daily_growth_rate,
          weeklyGrowthRate: item.weekly_growth_rate,
          monthlyGrowthRate: item.monthly_growth_rate,
          quarterlyGrowthRate: item.quarterly_growth_rate,
          semiannualGrowthRate: item.semiannual_growth_rate,
          annualGrowthRate1y: item.annual_growth_rate_1y,
          yearToDateGrowthRate: item.year_to_date_growth_rate,
          sinceInceptionGrowthRate: item.since_inception_growth_rate,
        }));
        setData(formatted);
        setFilteredData(formatted);
      })
      .catch((err) => {
        console.error('fetch fund list error:', err);
        message.error(`获取基金列表失败：${err.message || err.msg}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  // 2. 搜索：按 code 或 name 过滤
  const handleSearch = (value) => {
    const key = value.trim().toLowerCase();
    if (!key) {
      setFilteredData(data);
      return;
    }
    const filtered = data.filter(
      (item) =>
        item.code.toLowerCase().includes(key) ||
        item.name.toLowerCase().includes(key)
    );
    setFilteredData(filtered);
  };

  // 3. 点击“购买”弹窗
  const handleBuyFund = (fund) => {
    setSelectedFund(fund);
    setIsBuyModalVisible(true);
  };

  // 4. 点击“卖出”弹窗
  const handleSellFund = (fund) => {
    setSelectedFund(fund);
    setIsSellModalVisible(true);
  };

  // 5. 提交“购买”表单
  const handleBuySubmit = async (values) => {
    try {
      const userid = getUserId();
      if (!userid) {
        message.error('用户未登录，请先登录');
        return;
      }
      await $buyFund({
        userid: parseInt(userid, 10),
        products_id: selectedFund.code,
        products_name: selectedFund.name,
        quantity: values.quantity,
        price: selectedFund.unitNetValue,
        trade_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      });
      message.success('购买成功');
      setIsBuyModalVisible(false);
    } catch (err) {
      console.error('购买失败:', err);
      message.error(err.msg || '购买失败');
    }
  };

  // 6. 提交“卖出”表单
  const handleSellSubmit = async (values) => {
    try {
      const userid = getUserId();
      if (!userid) {
        message.error('用户未登录，请先登录');
        return;
      }
      await $sellFund({
        userid: parseInt(userid, 10),
        products_id: selectedFund.code,
        products_name: selectedFund.name,
        quantity: values.quantity,
        price: selectedFund.unitNetValue,
      });
      message.success('卖出成功');
      setIsSellModalVisible(false);
    } catch (err) {
      console.error('卖出失败:', err);
      message.error(err.msg || '卖出失败');
    }
  };

  // 7. 点击“基金代码”跳转到趋势可视化页面
  const handleCodeClick = (code) => {
    navigate(`/fund/trend?symbol=${code}`);
  };

  // 8. 渲染增长率为红/绿/灰 Tag
  const renderGrowthTag = (rate) => {
    const num = parseFloat(rate);
    if (num > 0) {
      return (
        <Tag color="red" className="change-tag positive">
          <RiseOutlined /> {rate}%
        </Tag>
      );
    } else if (num < 0) {
      return (
        <Tag color="green" className="change-tag negative">
          <FallOutlined /> {rate}%
        </Tag>
      );
    } else {
      return (
        <Tag color="default" className="change-tag neutral">
          {rate}%
        </Tag>
      );
    }
  };

  // 9. 渲染“单位净值”
  const renderUnitNetValue = (value, growthRate) => {
    const num = parseFloat(growthRate);
    const className =
      num > 0 ? 'positive-text' : num < 0 ? 'negative-text' : 'neutral-text';
    return <span className={`price-text ${className}`}>¥{value}</span>;
  };

  // 10. 渲染“累计净值”并加 Tooltip
  const renderCumNetValue = (value) => (
    <Tooltip title={`累计净值: ¥${value}`}>
      <span className="amount-text">¥{value}</span>
    </Tooltip>
  );

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (_, __, idx) => (
        <div className="index-cell">{idx + 1}</div>
      ),
    },
    {
      title: '基金信息',
      key: 'fundInfo',
      width: 240,
      render: (_, record) => (
        <div className="fund-info-cell">
          <div className="fund-code">
            <a
              onClick={() => handleCodeClick(record.code)}
              className="code-link"
            >
              {record.code}
            </a>
          </div>
          <div className="fund-name">{record.name}</div>
        </div>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <div className="action-buttons">
          <Button
            type="primary"
            size="small"
            icon={<ShoppingCartOutlined />}
            onClick={() => handleBuyFund(record)}
            className="buy-button"
          >
            买入
          </Button>
          <Button
            danger
            size="small"
            icon={<DollarOutlined />}
            onClick={() => handleSellFund(record)}
            className="sell-button"
          >
            卖出
          </Button>
        </div>
      ),
    },
    {
      title: '单位净值',
      dataIndex: 'unitNetValue',
      key: 'unitNetValue',
      width: 120,
      render: (val, record) =>
        renderUnitNetValue(val, record.dailyGrowthRate),
    },
    {
      title: '累计净值',
      dataIndex: 'cumulativeNetValue',
      key: 'cumulativeNetValue',
      width: 120,
      render: renderCumNetValue,
    },
    {
      title: '日增长率',
      dataIndex: 'dailyGrowthRate',
      key: 'dailyGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '近1周',
      dataIndex: 'weeklyGrowthRate',
      key: 'weeklyGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '近1月',
      dataIndex: 'monthlyGrowthRate',
      key: 'monthlyGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '近3月',
      dataIndex: 'quarterlyGrowthRate',
      key: 'quarterlyGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '近6月',
      dataIndex: 'semiannualGrowthRate',
      key: 'semiannualGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '近1年',
      dataIndex: 'annualGrowthRate1y',
      key: 'annualGrowthRate1y',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '今年来',
      dataIndex: 'yearToDateGrowthRate',
      key: 'yearToDateGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
    {
      title: '成立来',
      dataIndex: 'sinceInceptionGrowthRate',
      key: 'sinceInceptionGrowthRate',
      width: 100,
      render: (v) => renderGrowthTag(v),
    },
  ];

  return (
    <div className="fund-list-page">
      <div className="page-header">
        <div className="header-content">
          <div className="header-title">
            <FundOutlined className="header-icon" />
            <h1>基金实时列表</h1>
            <Badge count={filteredData.length} className="stock-count-badge" />
          </div>
          <div className="market-stats">
            <div className="stat-item">
              <ArrowUpOutlined />
              <span>实时更新</span>
            </div>
          </div>
        </div>
      </div>

      <Card className="stock-card" bordered={false}>
        <div className="search-section">
          <Search
            placeholder="输入基金代码或名称..."
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            className="stock-search"
            size="large"
          />
        </div>

        {loading ? (
          <div className="loading-container">
            <Spin size="large" tip="正在加载基金数据..." />
          </div>
        ) : (
          <div className="table-container">
            <Table
              rowKey="code"
              dataSource={filteredData}
              columns={columns}
              pagination={{
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 只基金，显示第 ${range[0]}-${range[1]} 条`,
              }}
              scroll={{ x: 'max-content', y: 600 }}
              className="stock-table"
              rowClassName={(record, index) => {
                const num = parseFloat(record.dailyGrowthRate);
                if (num > 0) return 'positive-row';
                if (num < 0) return 'negative-row';
                return 'neutral-row';
              }}
            />
          </div>
        )}
      </Card>

      {/* 购买弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <ShoppingCartOutlined />
            <span>购买基金</span>
          </div>
        }
        visible={isBuyModalVisible}
        onCancel={() => setIsBuyModalVisible(false)}
        footer={null}
        className="trade-modal buy-modal"
      >
        {selectedFund && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedFund.code}</div>
              <div className="stock-name-modal">{selectedFund.name}</div>
              <div className="current-price">
                当前单位净值: ¥{selectedFund.unitNetValue}
              </div>
            </div>
          </div>
        )}
        <Form onFinish={handleBuySubmit} layout="vertical" className="trade-form">
          <Form.Item
            label="购买份额"
            name="quantity"
            rules={[{ required: true, message: '请输入购买份额' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="请输入购买份额"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              icon={<ShoppingCartOutlined />}
              className="confirm-buy-btn"
            >
              确认购买
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 卖出弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <DollarOutlined />
            <span>卖出基金</span>
          </div>
        }
        visible={isSellModalVisible}
        onCancel={() => setIsSellModalVisible(false)}
        footer={null}
        className="trade-modal sell-modal"
      >
        {selectedFund && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedFund.code}</div>
              <div className="stock-name-modal">{selectedFund.name}</div>
              <div className="current-price">
                当前单位净值: ¥{selectedFund.unitNetValue}
              </div>
            </div>
          </div>
        )}
        <Form onFinish={handleSellSubmit} layout="vertical" className="trade-form">
          <Form.Item
            label="卖出份额"
            name="quantity"
            rules={[{ required: true, message: '请输入卖出份额' }]}
          >
            <InputNumber
              min={1}
              style={{ width: '100%' }}
              placeholder="请输入卖出份额"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button
              danger
              htmlType="submit"
              size="large"
              icon={<DollarOutlined />}
              className="confirm-sell-btn"
            >
              确认卖出
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default FundList;
